#if !MACOS
using H.NotifyIcon.Core;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.IO;

namespace IISLogs
{
    internal class Program
    {
        static TrayIconWithContextMenu? trayIcon;
        static Process? webApiProcess;
        const string WebApiUrl = "http://localhost:5000";
        static string lastClipboard = "";

        static async Task SubmitClipboard(string text)
        {
            using var client = new HttpClient();
            var content = new StringContent(text);
            try
            {
                await client.PostAsync("http://localhost:5000/clipboard", content);
            }
            catch (Exception ex)
            {
                Console.WriteLine("API提交失败: " + ex.Message);
            }
        }

        static async Task MonitorClipboard()
        {
            while (true)
            {
                string current = ClipboardHelper.GetText();
                if (!string.IsNullOrEmpty(current) && current != lastClipboard)
                {
                    lastClipboard = current;
                    await SubmitClipboard(current);
                    Console.WriteLine($"剪贴板已变更，内容已提交: {current}");
                }
                await Task.Delay(1000);
            }
        }

        static async Task Main(string[] args)
        {
            if (Environment.UserInteractive)
            {
                RunWithTray();
            }
            else
            {
                StartWebApi();
                _ = MonitorClipboard();
                await Task.Delay(-1); // 永久等待
            }
        }

        static void RunWithTray()
        {
            PopupMenuItem? autoStartItem = null;

            using var iconStream = H.Resources.Red_ico.AsStream();
            using var icon = new Icon(iconStream);
            trayIcon = new TrayIconWithContextMenu
            {
                Icon = icon.Handle,
                ToolTip = "IIS日志分析",
            };

            bool enabled = AutoStartHelper.IsAutoStartEnabled();
            string title = (enabled ? "✔ " : "") + "自动启动";
            autoStartItem = new PopupMenuItem(title, (_, _) =>
            {
                bool curr = AutoStartHelper.IsAutoStartEnabled();
                AutoStartHelper.SetAutoStart(!curr);
                autoStartItem.Text = (!curr ? "✔ " : "") + "自动启动";
            });

            trayIcon.ContextMenu = new PopupMenu
            {
                Items =
                {
                    new PopupMenuItem("打开分析面板", (_, _) => StartOrOpenWebApi()),
                    new PopupMenuItem("设置", (_, _) => ShowSettings()),
                    new PopupMenuSeparator(),
                    autoStartItem!,
                    new PopupMenuItem("关于我们", (_, _) => ShowAbout()),
                    new PopupMenuItem("检查更新", (_, _) => CheckUpdate()),
                    new PopupMenuSeparator(),
                    new PopupMenuItem("关闭并退出", (_, _) =>
                    {
                        StopWebApi();
                        trayIcon.Dispose();
                        Environment.Exit(0);
                    })
                },
            };
            trayIcon.Create();

            StartOrOpenWebApi();
            _ = MonitorClipboard();

            using var waitHandle = new System.Threading.ManualResetEvent(false);
            waitHandle.WaitOne();
        }

        // 安全通知方法
        static void SafeNotify(string title, string message, NotificationIcon icon)
        {
            if (Environment.UserInteractive && trayIcon != null && trayIcon.IsCreated)
                trayIcon.ShowNotification(title, message, icon);
        }

        // 判断webApiProcess是否有效
        static bool IsWebApiRunning()
        {
            try
            {
                return webApiProcess != null && !webApiProcess.HasExited;
            }
            catch (InvalidOperationException)
            {
                webApiProcess = null;
                return false;
            }
        }

        // 统一面板打开逻辑，使用IsWebApiRunning
        static void StartOrOpenWebApi()
        {
            if (IsWebApiRunning())
            {
                SafeNotify("WebAPI", "WebApi 已在运行，正在打开分析面板...", NotificationIcon.Info);
                OpenBrowser(WebApiUrl);
                return;
            }
            StartWebApi();
            OpenBrowser(WebApiUrl);
        }

        static void StartWebApi()
        {
            string logFile = Path.Combine(AppContext.BaseDirectory, "start_webapi_error.log");
            if (IsWebApiRunning())
            {
                SafeNotify("WebAPI", "WebApi 已在运行", NotificationIcon.Info);
                return;
            }

            string baseDir = AppContext.BaseDirectory;
            string exePath;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                exePath = Path.Combine(baseDir, "IISLogs.WebApi.exe");
            else
                exePath = Path.Combine(baseDir, "IISLogs.WebApi");

            try
            {
                if (!File.Exists(exePath))
                {
                    string msg = $"找不到 WebApi 可执行文件: {exePath}";
                    SafeNotify("WebAPI", msg, NotificationIcon.Error);
                    File.AppendAllText(logFile, $"{DateTime.Now:u} {msg}{Environment.NewLine}");
                    return;
                }

                webApiProcess = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = exePath,
                        UseShellExecute = false,
                        CreateNoWindow = true,
                        WorkingDirectory = baseDir
                    }
                };
                webApiProcess.Start();
                SafeNotify("WebAPI", "已启动 web api", NotificationIcon.Info);
                Console.WriteLine("打开 web api 命令触发");
                File.AppendAllText(logFile, $"{DateTime.Now:u} IISLogs.WebApi.exe 已启动, PID={webApiProcess.Id}{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                string msg = $"启动 WebApi 失败: {ex}";
                SafeNotify("WebAPI", "启动 web api 失败：" + ex.Message, NotificationIcon.Error);
                Console.WriteLine(msg);
                File.AppendAllText(logFile, $"{DateTime.Now:u} {msg}{Environment.NewLine}");
            }
        }

        static void StopWebApi()
        {
            if (IsWebApiRunning())
            {
                try
                {
                    webApiProcess!.Kill(true); // 结束AOT进程
                    SafeNotify("WebAPI", "已关闭 web api", NotificationIcon.Warning);
                    Console.WriteLine("关闭 web api 命令触发");
                }
                catch (Exception ex)
                {
                    SafeNotify("WebAPI", "关闭 web api 失败：" + ex.Message, NotificationIcon.Error);
                    Console.WriteLine("关闭 WebApi 失败: " + ex);
                }
            }
            webApiProcess = null;
        }

        static void ShowAbout()
        {
            SafeNotify("关于我们", "IIS日志分析 应用\n开发者: 魏水平\n版本: 1.0.0", NotificationIcon.Info);
        }

        static void ShowSettings()
        {
            SafeNotify("设置", ClipboardHelper.GetText(), NotificationIcon.Info);
        }

        static void CheckUpdate()
        {
            SafeNotify("检查更新", "当前已是最新版本", NotificationIcon.Info);
        }

        static void OpenBrowser(string url)
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    Process.Start(new ProcessStartInfo("cmd", $"/c start {url.Replace("&", "^&")}") { CreateNoWindow = true });
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    Process.Start("xdg-open", url);
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    Process.Start("open", url);
            }
            catch { }
        }
    }
}
#endif